// import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
const grant_type = 'client_credentials'
const client_id = '2MAXMYWoEGZDblzlvMq3yp3C'
const client_secret = 'tZllOuZ6panOnTlKRAQrUstwCx4Q5nKa'
const userinfo = wx.getStorageSync('userinfo')

// pages/post/post.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:"",
    show: false,
    teamname: "",
    type: ['线上', '线下'],
    team_type: "",
    team_max: "",//队伍限制人数
    team_had: "",//现有人数
    want: "",
    radio: 'QQ',
    number: '',
    des: '',
    imgList: [],
    token: null,
    base64: [],
    judgment: null,
    imagePath: [],
    address: '点击选择位置',
    longitude: 0, //经度
    latitude: 0, //纬度
    files: [],
    choose:0,
    fileIDs:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userinfo:userinfo._openid
    })
    var that = this
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=' + grant_type + '&client_id=' + client_id + '&client_secret=' + client_secret,
      method: 'POST',
      complete: function (res) {
        console.log('Request complete')
        },
      success: function (res) {
        console.log(res)
        const getToken = res.data.access_token
        that.setData({
          token: getToken //将access_token存到token中
          })
        },
        fail: function (res) {
          console.log('Fail to request !')
          console.log(res)
        }
      })
      this.setData({
        id:parseInt(new Date().getTime() / 1000)
      })
      console.log(this.data.id)
    
  },

  getValue: function (e) {
    this.setData({
      teamname: e.detail.value
    });
  },
  getMax: function (e) {
    let num = parseInt(e.detail.value)
    this.setData({
      team_max: num
    });
  },
  getHad: function (e) {
    let num = parseInt(e.detail.value)
    this.setData({
      team_had: num
    });
  },
  getWant: function (e) {
    this.setData({
      want: e.detail.value
    });
  },
  getNumber: function (e) {
    this.setData({
      number: e.detail.value
    });
  },
  getDes: function (e) {
    this.setData({
      des: e.detail.value
    });
  },

  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  onConfirm(e) { //选择器右上角的确定，点击确定获取值
    this.setData({
      team_type: e.detail.value,
      show: false
    })
  },
  onClick(event) {
    const {
      name
    } = event.currentTarget.dataset;
    this.setData({
      radio: name,
    });
  },

  recognition: function () {
    console.log('审核图像');
    var that = this;
    wx.chooseImage({
      count: 4,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        if (that.data.imagePath.length != 0) {
          that.setData({
            imagePath: that.data.imagePath.concat(res.tempFilePaths)
          })
        } else {
          that.setData({
            imagePath: res.tempFilePaths
          })
        }
        var Path = that.data.imagePath
        console.log(that.data.imagePath)
        Path.reverse()
        console.log(Path)
        if(that.data.imagePath.length != 0){
          for (let i =0;i <that.data.imagePath.length;i++){
            wx.getFileSystemManager().readFile({
              filePath: Path[i], //选择图片返回的相对路径
              encoding: 'base64', //编码格式
              success: res => { //成功的回调
                var image = res.data;
                console.log(image)
                // 图片审核
                wx.request({
                  url: 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' + that.data.token,
                  data: {
                    image: image,
                    imgType: 0,
                  },
                  header: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  method: 'POST',
                  success(res) {
                    console.log(res.data)
                      that.setData({
                        judgment: res.data.conclusion
                      })
                    console.log(that.data.judgment)
                    var g = that.data.choose
                    if (that.data.judgment != "合规") {
                      wx.showToast({
                        title: '图片不合规',
                        icon: 'error'
                      })
                      that.data.choose +=1
                    } else {
                      console.log(g)
                        that.setData({
                          files:that.data.imagePath[g],
                        })
                        that.setData({
                          imgList:that.data.imgList.concat(that.data.files)
                        })
                        console.log(that.data.imgList.length)
                        that.data.choose +=1
                    }
                    if(that.data.choose ==that.data.imagePath.length){
                      that.setData({
                        imagePath:[],
                        choose:0
                      })
                      console.log(that.data.imagePath)
                    }
                  },
                  fail: () => {
                    wx.hideLoading();
                    wx.showToast({
                      title: '图片识别失败，请重试！',
                      icon: 'none'
                    });
                  }
                })
              }
            })//转换base64以及图片审核
          }
        }
      }
    })
  },

  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },

  DelImg(e) {
    wx.showModal({
      title: '确定删除这张图片吗？',
      cancelText: '再看看',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },

  addressChange: function (e) {
    this.addressChoose(e);
  },
  addressChoose: function (e) {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          address: res.address, //地址
          longitude: res.longitude, //经度
          latitude: res.latitude, //纬度
        })
      },
      fail: function (e) {},
      complete: function (e) {
        console.log(e)
        console.log(that.data.address)
        console.log(that.data.latitude)
        console.log(that.data.longitude)
      }
    })
  },

  uploadPhoto(filePath) {
    return wx.cloud.uploadFile({
      cloudPath:`cover/${Date.now()}-${Math.floor(Math.random(0, 1) * 10000000)}.png`,
      filePath
    })
  },

  uploadImgs() {
    const uploadTask = this.data.imgList.map(item => this.uploadPhoto(item))
    Promise.all(uploadTask).then(result => {
      let resultImageUrls = [];
      for (const file of result) {
        resultImageUrls.push(file.fileID);
      }
      console.log(this.data.fileIDs)
    })
  },

  add_data: function (e) {
    if(wx.getStorageSync('userinfo').length == 0){
      wx.switchTab({
        url: '../post/post',
      })
      wx.showToast({
        title: '请登录',
        icon:"error"
      })
    }
    else if(this.data.team_max != 0 && this.data.team_had > this.data.team_max){
      wx.showModal({
        showCancel:false,
        title:'提示',
        content:'队伍人数超过上限'
      })
      console.log(typeof(this.data.team_max))
    }
    else if(this.data.number.length == 0 || this.data.number == false){
      wx.showModal({
        cancelColor: 'false',
        title:'提示',
        content:'请填写联系方式'
      })
    }
    else{
      const db = wx.cloud.database()
      const uploadTask = this.data.imgList.map(item => this.uploadPhoto(item))
      Promise.all(uploadTask).then(result => {
        let resultImageUrls = [];
        for (const file of result) {
          resultImageUrls.push(file.fileID);
        }
        this.setData({
          fileIDs:resultImageUrls
        })
          db.collection('detail').add({
            data: {
              name:wx.getStorageSync('userinfo').name,
              id:this.data.id,
              head:wx.getStorageSync('userinfo').avatarUrl,//头像
              title: this.data.teamname,//队伍名字
              type: this.data.team_type,//队伍类型
              member: this.data.team_max,//队伍限制人数
              now_member: this.data.team_had,//队伍现有人数
              need: this.data.want,//组队要求
              concat: this.data.number,//联系方式
              des: this.data.des,//活动描述
              pic:this.data.fileIDs,//云存储文件ID
              address: this.data.address,//地址
              longitude: this.data.longitude, //经度
              latitude: this.data.latitude, //纬度
              comment:[] //评论区
            },
            success: res => {
              var detail_id = res._id
              db.collection('user_info').where({
                _openid:userinfo._openid
              }).get()
              .then(res=>{
                var ls_list = res.data[0].mine_create
                var ls_list1 = res.data[0].mine_add
                ls_list1.splice(0,0,detail_id)
                ls_list.splice(0,0,detail_id)
                db.collection('user_info').where({
                  _openid:userinfo._openid
                }).update({
                  data:{
                    mine_create:ls_list,
                    mine_add:ls_list1
                  }
                })
              })
              wx.showToast({
                title: '发布成功',
              })
              .then(res=>{
                this.setData({
                  id:parseInt(new Date().getTime() / 1000),
                  show: false,
                  teamname: "",
                  type: ['线上', '线下'],
                  team_type: "",
                  team_max: "",//队伍限制人数
                  team_had: "",//现有人数
                  want: "",
                  radio: 'QQ',
                  number: '',
                  des: '',
                  imgList: [],
                  token: null,
                  base64: [],
                  judgment: null,
                  imagePath: [],
                  address: '点击选择位置',
                  longitude: 0, //经度
                  latitude: 0, //纬度
                  files: [],
                  choose:0,
                  fileIDs:[],
                })
                wx.switchTab({
                  url: '../home/home',
                  success:function(e){
                    let page = getCurrentPages().pop();
                    if(page == undefined || page == null)return;
                    page.onLoad();
                  }
                })
              })
            console.log(this.data.fileIDs)
            },
          })
      })
      .then(res=>{
        if (this.data.team_type == "线下"){
          db.collection('map_markers').add({
          data:{
              id:this.data.id,
              iconPath:"cloud://cloud1-8g1ky2ca399a275b.636c-cloud1-8g1ky2ca399a275b-1310564809/pic/1.png",
              longitude:this.data.longitude,
              latitude:this.data.latitude,
              width:30,
              height:30,
              callout: {
                content: this.data.teamname, 
                color: '#FF0202', 
                borderRadius: 3, 
                borderWidth: 1, 
                borderColor: '#FF0202', 
                bgColor: '#ffffff', 
                padding: 5, 
                textAlign: 'center',
                display:'ALWAYS'
              }
          }
        })
        let page = getCurrentPages().pop();
        if(page == undefined || page == null)return;
        page.onLoad();
      }
        else{
          console.log("寄")
        }
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTabBar().setData({
      active:1
    }) 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})